package cn.yunyichina.provider.message.utils;

public class SimpleHashTableNameGenerator {
    /**
     * 分表的子表数
     */
    public static final int subTableCount = 10;

    /**
     * 消息中心(通知中心)表名
     */
    public static final String SYS_MSG_CENTER = "SYS_MSG_CENTER";


    /**
     * 得到hsah子表名</p>
     * @param tableName      原表名<br>
     * @param splitKeyVal    hash取模的关键值(根据splitKeyVal值来取模)<br>
     * @param subTableCount  要拆分子表总数<br>
     * @param isNeedUniform  是否需要均匀散列<br>
     * @return
     */
    private static String getSplitTableName(String tableName, Object splitKeyVal, Integer subTableCount, Boolean isNeedUniform) {
        long hashVal = 0;
        if (splitKeyVal instanceof Number) {
            hashVal = Integer.parseInt(splitKeyVal.toString());
        } else {
            hashVal = splitKeyVal.toString().hashCode();
        }

        //斐波那契（Fibonacci）散列
        if (isNeedUniform) {
            hashVal = ( hashVal * 2654435769L ) >> 28;
        }

        //避免hashVal超出 MAX_VALUE = 0x7fffffff时变为负数,取绝对值
        hashVal = Math.abs(hashVal) % subTableCount;
        String splitableName = tableName + "_" + ( hashVal + 1 );
        return splitableName;
    }

    public static String getSysMsgCenterHashTable(String userId) {
        String hashTableName = getSplitTableName(SYS_MSG_CENTER, userId, subTableCount, true);
        return hashTableName;
    }

}
